package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.order.biz.TransOutboundInvoker;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.factory.OrderProcessPipelineFactory;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.form.CreateOrderRequest;
import com.cskaoyan.order.service.OrderCoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;


    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Override
    public String createOrder(CreateOrderRequest request) {
        //创建pipeline对象
        TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

        //启动pipeline
        invoker.start(); //启动流程（pipeline来处理）

        //获取处理结果
        AbsTransHandlerContext context = invoker.getContext();

        //从Context中获取订单Id
        String orderId = context.getOrderId();
        return orderId;
    }

    @Override
    public void cancelOrder(String orderId) {
        Order order = new Order();
        order.setOrderId(orderId);
        order.setStatus(5);
        orderMapper.updateByPrimaryKeySelective(order);
        // 其他关联的表也要改变status

        // 释放库存

        // 根据订单id去tb_order_item表，找出这个订单包含
        // 的商品种类，然后找到它们对应的商品id、选购数量
        List<OrderItem> orderItemList = orderItemMapper.queryByOrderId(orderId);
        if (orderItemList == null) {
            return;
        }
        for (OrderItem orderItem : orderItemList) {
            // 把order_item中的status字段改为5
            orderItemMapper.updateStockStatus(5, orderItem.getOrderId());
            // 根据商品id(itemId)找出这个商品的stock
            Stock stock = stockMapper.selectStock(orderItem.getItemId());
            // 库存变化数量
            Integer stockChangeNum = orderItem.getNum();
            // 做一些条件判断
            Long stockCount = stock.getStockCount();
            Integer lockCount = stock.getLockCount();
            if (stockCount + lockCount < 0) {
                // 库存数量有问题，抛出异常
                throw new BaseBusinessException(OrderRetCode.REQUISITE_PARAMETER_NOT_CORRECT.getCode(),
                        OrderRetCode.REQUISITE_PARAMETER_NOT_CORRECT.getMessage());
            }
            stock.setLockCount(lockCount - stockChangeNum);
            stock.setStockCount(stockCount + stockChangeNum);
            // updateByPrimaryKeySelective(stock)有问题，慎用
            //stockMapper.updateByPrimaryKeySelective(stock);
            // 自定义的更新stock方法
            stockMapper.updateStockNum(stock.getStockCount(), stock.getLockCount(), stock.getItemId());
        }

    }

    @Override
    public void deleteOrder(String orderId) {
        // 先通过orderid查出具体订单信息,然后将订单状态改为8,做逻辑删除
        // Order order = orderMapper.selectByPrimaryKey(orderId);
        // order.setStatus(8);
        // order.setUpdateTime(new Date());
        // orderMapper.updateByPrimaryKeySelective(order);
        // 先根据订单id查出来这个订单包含的商品
        orderMapper.deleteByPrimaryKey(orderId);
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", orderId);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
        // 把库存表的库存进行释放
        for (OrderItem orderItem : orderItems) {
            Integer num = orderItem.getNum();
            Stock stock = stockMapper.selectStock(orderItem.getItemId());
            Long stockCount = stock.getStockCount();
            Integer lockCount = stock.getLockCount();

            stock.setStockCount(stockCount + num);
            stock.setLockCount(lockCount - num);
            stockMapper.updateByPrimaryKeySelective(stock);
            orderItem.setStatus(2);
            orderItemMapper.updateByPrimaryKey(orderItem);

            stock.setStockCount(stockCount+num);
            stock.setLockCount(lockCount-num);
            Example example1 = new Example(Stock.class);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("itemId", orderItem.getItemId());
            stockMapper.updateByExampleSelective(stock,example1);
            orderItemMapper.deleteByPrimaryKey(orderItem.getId());

        }
        // 这两个与订单相关的表的数据也要删除
        orderShippingMapper.deleteByPrimaryKey(orderId);
    }

    @Override
    public void updateOrder(Integer status, String orderId) {
    }

}
